package com.bungarus.group.auth;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.Collections;
import java.util.Map;

public class SessionTokenAuthProvider implements AuthenticationProvider {

    private String key;

    public SessionTokenAuthProvider(String key) {
        this.key = key;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SessionToken auth = (SessionToken) authentication;
        Map<String, Long> IDsFromToken = SessionToken.parseIdentities((String)auth.getCredentials(), key);
        if(auth.getTenantId().longValue() == IDsFromToken.get(SessionToken.TENANT_ID).longValue()) {
                SessionToken authRequest = new SessionToken(
                        IDsFromToken.get(SessionToken.USER_ID),
                        IDsFromToken.get(SessionToken.TENANT_ID),
                        IDsFromToken.get(SessionToken.TIMESTAMP),
                        IDsFromToken.get(SessionToken.LIFETIME),
                        Collections.emptyList());
                if(System.currentTimeMillis() - IDsFromToken.get(SessionToken.TIMESTAMP) > IDsFromToken.get(SessionToken.LIFETIME)) {
                    authRequest.setAuthenticated(false);
                }
                else {
                    authRequest.setAuthenticated(true);
                }
                return authRequest;
        }
        return authentication;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass == SessionToken.class;
    }
}
